package com.inspire.sms.service.impl;

import com.inspire.sms.config.ChannelConfig;
import com.inspire.sms.service.IChannelSMSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Iterator;

/**
 * channel集合（相当于一个容器，存放了所有的通道）
 * 这里实现的思路和JDK中ArrayList的迭代器相同,
 *
 * @author inspire
 */
@Component
public class ChannelSMSServices implements Iterable<IChannelSMSService> {

	@Autowired
	private ChannelConfig channelConfig;

	@Autowired
	private ApplicationContext applicationContext;

	/**
	 * 批量发送的通道
	 * @return
     */
	public IChannelSMSService getBatchSendable() {
		return (IChannelSMSService) applicationContext.getBean(channelConfig.getBatchSend());
	}

	@Override
	public Iterator<IChannelSMSService> iterator() {
		return new Itr();
	}

	/**
	 * 匿名内部类,
	 * 泛型:IChannelSMSService ---> 通道集合中只能放通道,即IChannelSMSService的实现类
	 */
	private class Itr implements Iterator<IChannelSMSService> {

		/**
		 * 初始值为0
		 */
		int i;

		/**
		 * i = 通道的数量 --->所有的通道都被遍历了
		 * @return
         */
		@Override
		public boolean hasNext() {
			return i < channelConfig.getAvailable().size();
		}

		/**
		 * 每遍历一个通道后 i 自增1
		 * @return
         */
		@Override
		public IChannelSMSService next() {

			return (IChannelSMSService) applicationContext.getBean(channelConfig.getAvailable().get(i++));
		}
	}

}
